package com.itheima.ydd.controller;


import com.itheima.ydd.common.ResultData;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {

    @Value("${ydd.path}")
    private String path;

    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public ResultData upload(MultipartFile file) throws IOException {
        //获取文件名
        String originalFilename = file.getOriginalFilename();
        //获取文件格式
        String fileType = originalFilename.substring(originalFilename.lastIndexOf("."));
        //得到文件名
        String fileName = UUID.randomUUID().toString() + fileType;
        //如果不存在进行创建文件夹
        File file1 = new File(path);
        if (!file1.exists()) {
            file1.mkdirs();
        }
        HashMap<String, Object> hashMap = new HashMap<>();

        //上传文件
        file.transferTo(new File(path + fileName));
        hashMap.put("savePath","upload/images/"+fileName);
        hashMap.put("name", originalFilename);
        hashMap.put("mime", file.getContentType());
        hashMap.put("size", file.getSize());

        return ResultData.ok("", hashMap);
    }





}
